package com.yzkj.cpjxc.business.framework.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Web Service 工具类
 */
public class WsUtils {
	
	public static void main(String[] args) throws Exception {
		
	}
	
	public static String replace(String reponseXml) {
		reponseXml = StringUtils.replace(reponseXml, "&lt;", "<");
		reponseXml = StringUtils.replace(reponseXml, "&gt;", ">");
		return reponseXml;
	}

	public static Object call(String urlstr, String requestXml, boolean needEncrypt) throws Exception {
		String result = "";
		try {
			// 创建URL
			URL url = new URL(urlstr);
			
			// 根据URL创建连接
			HttpURLConnection huc = (HttpURLConnection) url.openConnection();
			
			// 设置连接主机超时（单位：毫秒）: 5秒
			huc.setConnectTimeout(50000);
			// 设置从主机读取数据超时（单位：毫秒）: 5秒
			huc.setReadTimeout(50000);
			
			byte[] buf = null;
			// 如果报文需要加密
			buf = requestXml.getBytes();
			
			huc.setUseCaches(false);
			huc.setRequestProperty("Content-Length", String.valueOf(buf.length));
			huc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
			huc.setRequestProperty("Accept-Charset", "utf-8");
			huc.setRequestProperty("soapActionString", "http://dh.webservice.eking.org/");
			huc.setRequestMethod("POST");
			huc.setDoOutput(true);
			huc.setDoInput(true);
			
			OutputStream out = huc.getOutputStream();
			
			out.write(buf);
			out.close();
			
			InputStream is = huc.getInputStream();
			
			byte[] datas = IOUtils.toByteArray(is);
			result = new String(datas, "UTF-8");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		//返回结果
		return result;
	}
}

